import { PrismaClient } from "@prisma/client";
import { formatDate, formatDateToTimestamp } from "../utils/format";

const prisma = new PrismaClient();

export const getConversations = async (userId: number) => {
  const list = await prisma.conversations.findMany({
    where: { user_id: userId },
    orderBy: { updated_at: "desc" },
  });

  const privateIds = list.filter((c) => c.type === 1).map((c) => c.target_id);
  const groupIds = list.filter((c) => c.type === 2).map((c) => c.target_id);

  // 批量获取 user / group 信息
  const users = await prisma.users.findMany({
    where: { id: { in: privateIds } },
    select: { id: true, username: true, avatar: true },
  });

  const groups = await prisma.groups.findMany({
    where: { id: { in: groupIds } },
    include: {
      group_members: {
        include: {
          users: {
            select: {
              id: true,
              username: true,
              avatar: true
            }
          }
        }
      }
    },
    // select: { id: true, name: true, avatar: true },
  });

  const userMap = Object.fromEntries(users.map((u) => [u.id, u]));
  const groupMap = Object.fromEntries(groups.map((g) => [g.id, g]));

  // 映射为前端结构
  return list.map((c) => {
    const info =
      c.type === 1
        ? userMap[Number(c.target_id)]
        : groupMap[Number(c.target_id)];
    return {
      id: c.id,
      type: c.type,
      target_id: c.target_id,
      targetInfo: info,
      name: info?.username || info?.name || "未知",
      avatar: info?.avatar || "",
      last_message: c.last_message,
      unread_count: c.unread_count,
      updated_at: formatDateToTimestamp(c.updated_at),
    };
  });
};

export const createOrUpdateConversation = async (input: {
  user_id: number;
  target_id: number;
  type: number; // 1私聊 2群聊
  last_message?: string;
}) => {
  const exist = await prisma.conversations.findFirst({
    where: {
      user_id: input.user_id,
      target_id: input.target_id,
      type: input.type,
    },
  });

  if (exist) {
    return prisma.conversations.update({
      where: { id: exist.id },
      data: {
        last_message: input.last_message,
        unread_count: { increment: 1 },
        updated_at: new Date(),
      },
    });
  } else {
    return prisma.conversations.create({
      data: {
        user_id: input.user_id,
        target_id: input.target_id,
        type: input.type,
        last_message: input.last_message,
      },
    });
  }
};

export const resetUnread = async (userId: number, conversation_id: number) => {
  await prisma.conversations.updateMany({
    where: { user_id: userId, id: conversation_id },
    data: { unread_count: 0 },
  });
};

export const deleteConversation = async (userId: number, id: number) => {
  return prisma.conversations.deleteMany({
    where: {
      id,
      user_id: userId,
    },
  });
};
